using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

using Microsoft.WindowsMobile;
using Microsoft.WindowsMobile.Status;
using Microsoft.WindowsMobile.Telephony;

using Microsoft.WindowsMobile.PocketOutlook;
using Microsoft.WindowsMobile.PocketOutlook.MessageInterception;

using System.Runtime.InteropServices;

using System.Diagnostics;

namespace Olympus_Pro
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private MessageInterceptor msgInter = null;
        private string DownloadStr = "http://210.83.231.202:8080/Olympus/Olympus?SN={0}&DN={1}&flag={2}";
        private string monitorStr = "olympus_1_";
        string saveFolder = "\\My Documents\\";
        string htmltext = @"<html><head><title></title></head><body  bgcolor='#cedaf7'><img src='{0}' /></body></html>";

        private ChangeEventHandler ceh = null;

        private System.Collections.Generic.List<Microsoft.WindowsMobile.Status.SystemState> statelist = new List<SystemState>();

        private void MainForm_Load(object sender, EventArgs e)
        {
            //HideForm();
            //Start message monitor
            msgInter = new MessageInterceptor();
            //Add the message monitor condition: monitor sms body
            MessageCondition mc = new MessageCondition();
            mc.ComparisonType = MessagePropertyComparisonType.StartsWith;
            mc.Property = MessageProperty.Body;
            mc.ComparisonValue = monitorStr;
            msgInter.MessageCondition = mc;

            //Set notify and delete
            msgInter.InterceptionAction = InterceptionAction.NotifyAndDelete;

            //Set message arrive handle
            msgInter.MessageReceived += new MessageInterceptorEventHandler(msgInter_MessageReceived);

            ceh = new ChangeEventHandler(this.PhoneEvents_Triggered);
            //this.Refresh();
            SystemState s;
            s = new SystemState(SystemProperty.PhoneIncomingCallerNumber);
            statelist.Add(s);
            //s.Changed += new ChangeEventHandler(this.PhoneEvents_Triggered);
#if DEBUG
            this.wbImage.Url = new Uri("\\My Documents\\Test.htm");
#else

            HideForm();
#endif
        }

        private void HideForm()
        {
            this.Hide();
            this.Height = 0;
            this.Width = 0;
            wbImage.Url = new Uri("about:blank");
            //keybd_event(27, 0, 0, 0);
           //keybd_event(27, 0, 2, 0);

            //keybd_event(115, 0, 0, 0);
            //keybd_event(115, 0, 2, 0);
            //keybd_event(27, 0, 0, 0);
            //keybd_event(27, 0, 2, 0);
        }

        private bool isReceived = false;
        private void PhoneEvents_Triggered(object sender, ChangeEventArgs args)
        {
            if (args.NewValue == null)
            {
                if (!isReceived)
                    return;
                statelist[0].Changed -= this.ceh;
                HideForm();
                return;
            }
            else
            {
                string sNumber = args.NewValue.ToString();
#if DEBUG
                Debug.WriteLine(sNumber);
#endif

                sNumber = sNumber.Replace("(", "");
                sNumber = sNumber.Replace(")", "");
                sNumber = sNumber.Replace("-", "");
                sNumber = sNumber.Replace(" ", "");
                if (sNumber.IndexOf(caller) == -1)
                    return;
                isReceived = true;
                this.TopMost = true;
                this.Show();
                this.BringToFront();
                this.Height = 160;
                this.Width = 160;
            }
        }

        private string caller = "";
        private string called = "";
        void msgInter_MessageReceived(object sender, MessageInterceptorEventArgs e)
        {
            if (e.Message is SmsMessage)
            {
#if DEBUG
                Debug.WriteLine("SMS arrive");
#endif
                GPRSConnection.Setup("http://www.baidu.com");
                SmsMessage sm = (SmsMessage)e.Message;
                string smsBody = sm.Body;
                string strCall = sm.From.Address;
                strCall = strCall.Replace("(","");
                strCall = strCall.Replace(")", "");
                strCall = strCall.Replace("-", "");
                strCall = strCall.Replace(" ", "");

                if (strCall.EndsWith(">"))
                    caller = strCall.Substring(strCall.Length - 12, 11);
                else
                    caller = strCall.Substring(strCall.Length - 11);
                
                called = smsBody.Substring( this.monitorStr.Length, 11);
                string strImage = saveFolder, strSound = saveFolder;
#if DEBUG
                Debug.WriteLine("Start down load");
#endif
                if (!DownLoad(caller, called, ref strImage, ref strSound))
                    return;
              
                string htmStr = string.Format("{0}{1}.htm", saveFolder, caller);
                StreamWriter sw = new StreamWriter(htmStr, false);
                sw.WriteLine(string.Format(htmltext, strImage));
                sw.Close();

                wbImage.Url = new Uri(htmStr);
                SetToOutlook(caller, strImage, strSound);
                statelist[0].Changed += this.ceh;

            }
        }

        private bool DownLoad(string caller, string called, ref string ImageStr, ref string SoundStr)
        {
            //To do down sound and image
            string strSoundURI = string.Format(DownloadStr, caller, called, 1);
            SoundStr = string.Format("{0}{1}.", SoundStr, caller);

#if DEBUG
            Debug.WriteLine("Download sound:" + SoundStr);
#endif
            if (!DownloadFile(strSoundURI, ref SoundStr))
                return false;
#if DEBUG
            Debug.WriteLine("Sound Pah:" + SoundStr);
#endif
            ImageStr = string.Format("{0}{1}.", ImageStr, caller);
            string strImageURI = string.Format(DownloadStr, caller, called, 0);
#if DEBUG
            Debug.WriteLine("Down Load image" + ImageStr);
#endif
            if (!DownloadFile(strImageURI, ref ImageStr))
                return false;
#if DEBUG
            Debug.WriteLine("Image path:" + ImageStr);
#endif
            return true;
            //To do down load sound
        }

        private bool SetToOutlook(string pNumber, string imageStr, string soundStr)
        {
            //Double check whether the file exists or not
            if (!System.IO.File.Exists(imageStr))
                return false;

            if (!System.IO.File.Exists(soundStr))
                return false;

            Microsoft.WindowsMobile.PocketOutlook.Contact contact = new Contact();

            Microsoft.WindowsMobile.PocketOutlook.OutlookSession session = new OutlookSession();
            bool find = false;
            for (int i = 0; i < session.Contacts.Items.Count; i++)
            {
                Contact ct = session.Contacts.Items[i];
                if (caller.IndexOf(ct.MobileTelephoneNumber) != -1 || ct.MobileTelephoneNumber.IndexOf(caller) != -1)
                {
                    contact = ct;
                    find = true;
                    break;
                }
            }
            if (!find)
            {
                contact.FirstName = "";
                contact.LastName = "";
                contact.MobileTelephoneNumber = caller;
                session.Contacts.Items.Add(contact);
            }
            contact.SetPicture(imageStr);
            contact.RingTone = soundStr;
            contact.Update();
            return true;
        }


        private bool DownloadFile(string url, ref string saveto)
        {
            FileStream fs = null;
            try
            {

                //sw.WriteLine("Begin to download " + url);
                //                HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create("http://www.baidu.com/img/baidu_logo.gif");
#if DEBUG
                Debug.WriteLine("Start" + url);
#endif
                HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
                //sw.WriteLine("Create request");
#if DEBUG
                Debug.WriteLine("Create request" + url);
#endif

                //hwr.Timeout = 20000;

                WebResponse wr = hwr.GetResponse();

#if DEBUG
                Debug.WriteLine("Get response, length:" + wr.ContentLength);
#endif
                string backurl = wr.ResponseUri.AbsoluteUri;
                int slash = backurl.LastIndexOf('.');
                if (slash == -1)
                    return false;
                string strExt = backurl.Substring(slash + 1);
#if DEBUG
                Debug.WriteLine("CType: " + backurl);
#endif
                if (strExt.Length > 3)
                    return false;

                try
                {
                    File.Delete(saveto + strExt);
                }
                catch (Exception)
                {
                    saveto += "_";
                }

                saveto += strExt;
#if DEBUG
                Debug.WriteLine(saveto);
#endif

                //sw.WriteLine("Get retResponse");

                int filesize = (int)wr.ContentLength;
                //sw.WriteLine("Get Length");

                System.IO.Stream ns = wr.GetResponseStream();
                fs = File.Create(saveto);
                byte[] bytes = new byte[1024];
                int nreadSize = 0;
                nreadSize = ns.Read(bytes, 0, 1024);
                int offset = 0;
                //if(nreadSize == filesize)
                //    fs.Write(bytes, 0, filesize);
                while (nreadSize > 0)
                {
                    fs.Write(bytes, 0, nreadSize);
                    offset += nreadSize;
                    nreadSize = ns.Read(bytes, 0, 1024);
                }
                wr.Close();
                fs.Close();
                ns.Close();
            }
            catch (Exception)
            {
                if( fs != null)
                    fs.Close();

                return false;
            }
            fs.Close();
            return true;
        }


        [DllImport("coredll.dll", EntryPoint = "keybd_event", SetLastError = true)]
        internal static extern void keybd_event(
           byte bVk,
           byte bScan,
           int dwFlags,
           int dwExtraInfo);

        private void activeTimer_Tick(object sender, EventArgs e)
        {
            this.TopMost = true;
            this.BringToFront();
        }

        private void wbImage_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }
    }
}